<template>
    <el-row :gutter="20" style="padding: 10px; box-sizing: border-box;margin: 0px">
        <el-form ref="form" label-width="80px">
            <el-col :span="10" class="mt">
                <el-form-item label="卡项名称">
                    <el-input v-model="form.name" placeholder="请输入卡项名称"></el-input>
                </el-form-item>
                <el-form-item label="卡项编号">
                    <el-input v-model="form.number" placeholder="请输入卡项编号"></el-input>
                </el-form-item>
                <el-form-item label="卡有效期" v-if="type == 1">
                    <el-input v-model="form.validity" placeholder="请输入期卡有效期"></el-input>
                </el-form-item>
                <el-form-item label="初始价格">
                    <el-input v-model="form.price" placeholder="请输入初始金额" @change="xin"></el-input>
                </el-form-item>
                <el-form-item label="销售提点">
                    <el-radio-group v-model="form.tdtype">
                        <el-radio :label="1">百分比提点</el-radio>
                        <el-radio :label="2">固定金额提点</el-radio>
                    </el-radio-group>
                    <el-input v-model="form.percent" v-if="form.tdtype==1" placeholder="请输入销售百分比提成(0 ~ 100)"></el-input>
                    <el-input v-model="form.fixed" v-else placeholder="请输入销售固定金额提成"></el-input>
                </el-form-item>
                <el-form-item label="卡项描述">
                    <el-input type="textarea" v-model="form.remarks" placeholder="请输入当前卡项描述"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="14" class="mt">
                <el-table :data="form.slist" height="400">
                    <el-table-column prop="number" label="编号"></el-table-column>
                    <el-table-column prop="name" label="项目"></el-table-column>
                    <el-table-column prop="price" label="标准价格"></el-table-column>
                    <el-table-column prop="disprice" label="折扣价格" v-if="type == 2">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.disprice" size="mini" @change="geng"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="xhprice" label="消耗价格" v-if="type == 1">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.xhprice" size="mini" placeholder="自定消耗价格"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="num" label="次数" v-if="type == 2">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.num" size="mini" @change="geng"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="移除">
                        <template slot-scope="scope">
                            <el-button type="danger" icon="el-icon-close" size="mini" @click="rmrow(scope.$index)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="block right mt">
                    <el-button size="mini" type="success" icon="el-icon-plus" class="fl" @click="addsubject">添加项目</el-button>
                    
                    <el-button size="mini" type="primary" icon="el-icon-upload" @click="onSubmit" style="float:right">
                        <span v-if="!istijiao">立即创建</span>
                        <span v-else>确定修改</span>
                    </el-button>
                    <el-button size="mini" type="danger" icon="el-icon-close" @click="closeWin"  style="float:right">取消关闭</el-button>
                </div>
            </el-col>
        </el-form>
    </el-row>
</template>
<script>
import C from '@/common/common.js'

export default {
  name: 'addCard',
  data () {
    return {
      form: {
        id: 0,
        number: '',
        name: '',
        price: '',
        percent: '',
        fixed: '',
        validity: 365,
        remarks: '',
        slist: [],
        tdtype: 1
      },
      type: 1, // 1：期卡，2：次卡
      dels: [],
      istijiao: false
    }
  },
  methods: {
    onSubmit: async function () {
      if (this.form.name == '') {
        C.error('请输入卡项名称')
        return false
      }

      if (this.form.number == '') {
        C.error('卡项编号不能为空')
        return false
      }

      if (!this.form.slist.length) {
        C.error('请添加项目')
        return false
      }

      if (!/^[1-9]+\d*(\.)?\d*$/.test(this.form.price)) {
        C.error('请正确输入售卡金额')
        return false
      }

      if (this.form.tdtype == 1) {
        if (!/^(\d|[1-9]\d|100)$/.test(this.form.percent)) {
          C.error('请正确输入售卡百分比提成')
          return false
        }
      } else {
        if (!/^([1-9]\d*|0)(\.\d+)?$/.test(this.form.fixed)) {
          C.error('请正确输入售卡固定金额提成')
          return false
        }
      }

      if (this.form.fixed * 1 > this.form.price * 1) {
        C.error('固定金额超出了售卡价格，请重新输入')
        return false
      }

      if (this.type == 1 && this.form.validity <= 0) {
        C.error('有效天数必须大于零')
        return false
      }

      if (this.type == 2) {
        this.form.slist.forEach((row) => {
          if (row.num <= 0) {
            C.error('次数必须大于零')
            return false
          }
          if (row.disprice <= 0) {
            C.error('折扣价格大于零')
            return false
          }
        })
      }
      // 计算期卡项目卡耗
      let qkxhprice = false

      if (this.type == 1) {
        let qkxmzj = 0
        this.form.slist.forEach((v) => {
          qkxmzj += v.price * 1
          if (!/^\d*(\.\d*)?$/.test(v.xhprice * 1)) qkxhprice = true
        })
        let dczj = this.form.price / qkxmzj
        this.form.slist.forEach((s) => {
          s.amount = Number(s.price * dczj).toFixed(4)
          s.disprice = 0
        })
      }

      if (qkxhprice) {
        C.error('消耗价格不正确')
        return false
      }
      let selectItem = this.form.slist
      for (var i = 0; i < selectItem.length; i++) {
        let discount = parseInt(selectItem[i].amount)
        if (selectItem[i].xhprice > discount || selectItem[i].xhprice > selectItem[i].price) {
          C.error('消耗价格应小于标准价格、小于折扣价格,折扣后价格为' + '"' + discount + '"')
          return false
        }
      }
      if (!this.form.id * 1) {
        // create shop cards
        let data = await C.ajax('/shop/card/createcard', { data: JSON.stringify(this.form), type: this.type }, 'post')
        if (data) {
          C.closeBrowserWindow(data)
        }
      } else {
        // edit shop cards
        let data = await C.ajax('/shop/card/editcard', { data: JSON.stringify(this.form), type: this.type, dels: JSON.stringify(this.dels) }, 'post')
        if (data) {
          C.closeBrowserWindow(data)
        }
      }
    },
    addsubject: async function () {
      let data = await C.openBrowserWindow('/selectSubject', {}, { width: 1200, height: 880, useSpa: false, spaModel: 'shop', transparent: true, frame: false })
      if (data) {
        data.forEach((row) => {
          if (C.inarray({ subjectid: row.id }, this.form.slist) < 0) {
            let catchData = {
              subjectid: row.id,
              name: row.name,
              number: row.number,
              price: row.price,
              disprice: row.price,
              num: 1,
              xhprice: 0
            }
            this.form.slist.push(catchData)
          }
        })
        this.geng()
      }
    },

    rmrow: function (index) {
      if (this.form.slist[index].id) {
        this.dels.push(this.form.slist[index].id)
      }
      this.form.slist.splice(index, 1)
      this.xin()
    },
    closeWin: function () {
      C.closewin()
    },
    geng: function () {
      let tot = 0
      if (this.form.slist.length) {
        if (this.type == 2) {
          this.form.slist.forEach((v) => {
            tot += v.disprice * v.num
          })
        } else {
          this.form.slist.forEach((v) => {
            tot += v.price * 1
          })
        }
      }
      this.form.price = Number(tot).toFixed(2)
    },
    xin: function () {
      if (this.form.slist.length && this.form.price * 1) {
        let yuan = 0,
          bai = 0
        // 计算次卡总价
        if (this.type == 2) {
          this.form.slist.forEach((v) => {
            yuan += v.price * v.num
          })
          bai = this.form.price / yuan
          this.form.slist.forEach((s) => {
            s.disprice = Number(s.price * bai).toFixed(2)
          })
        }
      } else {
        this.form.price = 0
      }
    }
  },
  mounted: async function () {
    let data = C.getDatas()
    this.type = data.type
    this.istijiao = !!data.id
    if (data.id) {
      let res = await C.ajax('/shop/card/lookcardinfo', { id: data.id })
      if (res) {
        this.form.id = res.info.id
        this.form.name = res.info.name
        this.form.number = res.info.number
        this.form.price = res.info.price
        this.form.percent = Number(res.info.percent * 100).toFixed(0)
        this.form.fixed = res.info.fixed
        this.form.validity = res.info.validity
        this.form.remarks = res.info.remarks
        this.form.tdtype = res.info.tdtype
        res.list.forEach((v) => {
          this.form.slist.push({
            id: v.id,
            subjectid: v.subjectid,
            name: v.name,
            number: v.number,
            price: v.price,
            disprice: v.disprice,
            num: v.num,
            xhprice: v.xhprice
          })
        })
      }
    }
  }
}
</script>